import { useState, useEffect } from 'react'
import { storage } from '@/services/storage'

export const useStudyStats = () => {
  const [decks, setDecks] = useState([])
  const [dailyStats, setDailyStats] = useState({
    totalDue: 0,
    deckStats: []
  })

  const calculateStats = () => {
    const loadedDecks = storage.getDecks()
    setDecks(loadedDecks)
    
    const stats = loadedDecks.map(deck => {
      const cards = storage.getCardsByDeck(deck.id)
      const dueCards = cards.filter(card => new Date(card.nextReview) <= new Date())
      return {
        deckId: deck.id,
        deckName: deck.name,
        dueCount: dueCards.length,
        totalCards: cards.length
      }
    })
  
    setDailyStats({
      totalDue: stats.reduce((sum, stat) => sum + stat.dueCount, 0),
      deckStats: stats
    })
  }

  useEffect(() => {
    calculateStats()
  }, [])

  return { decks, dailyStats, refreshStats: calculateStats }
}